package com.dragon.app.concurrent;

import java.util.concurrent.atomic.AtomicInteger;


public class AtomicTest {
	

	public static void main(String[] args) {
		
		DataTest data = new DataTest();

		//开20个线程，每个循环10000次，如果是原子性，理论结果应该是200000
		for (int i = 0; i < 20; ++i) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					for (int j = 0; j < 10000; j++) {
						data.decrement();
					}
				}
			}).start();
		}
		

		while (Thread.activeCount() > 2) {
			Thread.yield();
		}

		System.out.println("exit...");
		System.out.println("data.number:" + data.number);
		System.out.println("data.atomicNumber:" + data.atomicNumber.get());
	}
	
	static class DataTest{
		volatile int number = 0; //volatile保证可见和有序性，不保证原子性
		AtomicInteger atomicNumber = new AtomicInteger(0); //Atomic中的cas操作保证原子性
		
		public void decrement() {
			this.number++;
			this.atomicNumber.incrementAndGet();
		}
	}

}
